package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtil;
import com.itheima.utils.Md5Util;
import com.itheima.utils.UserHolder;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 用户注册
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,
                           @Pattern(regexp = "^\\S{5,16}$") String password) {
        User user = userService.findUserByUsername(username);
        if(user == null) {
            // 没有占用，则进行注册操作
            userService.register(username, password);
            return Result.success();
        } else {
            // 被占用
            return Result.error("用户名已被占用");
        }
    }

    /**
     * 用户登录
     *      如果登录成功，要返回登陆令牌
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username,
                                @Pattern(regexp = "^\\S{5,16}$") String password) {
        User user = userService.findUserByUsername(username);
        if(user == null) {
            // 用户不存在
            return Result.error("用户或密码错误");
        }
        if(!Md5Util.getMD5String(password).equals(user.getPassword())) {
            // 密码错误
            return Result.error("用户或密码错误");
        }
        // 登录成功：【生成jwt token令牌并返回】
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("username", user.getUsername());
        String token = JwtUtil.genToken(claims);
        // 并且把token存入到redis当中，过期时间设为12小时
        stringRedisTemplate.opsForValue().set(username, token, 12, TimeUnit.HOURS);
        return Result.success(token);
    }

    /**
     * 获取用户详细信息
     * @return
     */
    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/) {
        /*// 根据token获取用户username
        Map<String, Object> map = JwtUtil.parseToken(token);
        String username = (String) map.get("username");
        User user = userService.findUserByUsername(username);*/

        Map<String, Object> map = UserHolder.get();
        String username = (String) map.get("username");
        User user = userService.findUserByUsername(username);
        return Result.success(user);
    }

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        userService.update(user);
        return Result.success();
    }

    /**
     * 更新用户头像
     * @param avatarUrl
     * @return
     */
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    /**
     * 修改用户密码
     * @param params
     * @return
     */
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params) {
        // 参数校验
        String oldPwd = params.get("old_pwd");// 原始密码
        String newPwd = params.get("new_pwd");// 新密码
        String rePwd = params.get("re_pwd");// 确认新密码
        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要的参数");
        }

        // 验证原密码是否正确
        Map<String, Object> map = UserHolder.get();
        String username = (String) map.get("username");
        User user = userService.findUserByUsername(username);
        if(!user.getPassword().equals(Md5Util.getMD5String(oldPwd))) {
            return Result.error("原密码填写不正确");
        }
        // 验证两次新密码是否一致
        if(!newPwd.equals(rePwd)) {
            return Result.error("两次新密码填写不一致");
        }
        // 更新密码
        userService.updatePwd(newPwd);
        // 更新密码后，要把存储在redis中的令牌删除，使之失效
        stringRedisTemplate.opsForValue().getOperations().delete(username);
        return Result.success();
    }

}
